<template>
    <div class="common-page page-staff-work-order-add" v-loading.fullscreen="loading">
        <div class="common-page__head">
            <comp-paths class="route" :paths="['/staff/work', '/staff/work/orders/type1', $route.fullPath]"></comp-paths>
            <div class="title"></div>
        </div>
        <div class="common-page__body"></div>
        <comp-dialog title="提交事项" ref="order" @close="addOrder('end')">
            <el-form size="small" label-width="112px" style="margin-right: 20px" @submit.native.prevent v-if="order">
                <el-form-item label="企业/项目：" required>
                    <el-tag style="margin-right: 10px; max-width: 450px" disable-transitions v-if="order.company.id">{{ order.company.name }}</el-tag>
                    <el-button type="plain" icon="el-icon-refresh" @click="addOrder('order-company')" v-if="order.company.id">更换企业/项目</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="addOrder('order-company')" v-else>选择企业/项目</el-button>
                </el-form-item>
                   <!-- <el-form-item label="问题来源：">
                <el-select v-model="order.wtly" style="width: 600px" placeholder="请选择" @change="addOrder('validate')">
                        <el-option key="1" label="区县级" value="1"></el-option>
                        <el-option key="2" label="市级" value="2"></el-option> 
                </el-select>
              </el-form-item> -->
                <el-form-item label="问题层级：" required>
                    <el-select v-model="order.lev" style="width: 600px" placeholder="请选择" @change="addOrder('order-dept')">
                        <el-option key="1" label="区县级" value="1"></el-option>
                        <el-option key="2" label="市级" value="2"></el-option>
                        <el-option key="3" label="自治区级" value="3"></el-option>
                    </el-select>
                </el-form-item>
<!--                <el-form-item label="负责工作队：" required>-->
<!--                    <el-select v-model="order.dept.id" style="width: 600px" placeholder="请选择" @change="addOrder('order-dept')">-->
<!--                        <el-option v-for="data in order.company.depts" :key="data.id" :label="data.name" :value="data.id"></el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->
<!--                <el-form-item label="负责服务专员：" required>-->
<!--                    <el-select v-model="order.handler.id" style="width: 600px" placeholder="请选择" @change="addOrder('validate')">-->
<!--                        <el-option v-for="data in handlers" :key="data.id" :label="data.flag" :value="data.id"></el-option>-->
<!--                    </el-select>-->
<!--                </el-form-item>-->
                <el-form-item label="事项标题：" required>
                    <el-input type="textarea" v-model="order.title" style="width: 600px" placeholder="请输入" :maxlength="100" :rows="2" resize="none" :readonly="loading" @change="addOrder('validate')"></el-input>
                </el-form-item>
                <el-form-item label="事项描述：" required>
                    <el-input type="textarea" v-model="order.content" style="width: 600px" placeholder="请输入" :maxlength="1000" :rows="10" resize="none" :readonly="loading" @change="addOrder('validate')"></el-input>
                </el-form-item>
                <el-form-item label="事项分类：" required>
                    <div style="width: 600px">
                        <el-checkbox v-for="tag in tags" :key="tag.id" v-model="tag.selected" style="margin-right: 20px" :label="tag.name" :disabled="order.tags.length >= 1 && !tag.selected" @change="addOrder('validate')"></el-checkbox>
                    </div>
                </el-form-item>
                <el-form-item label="事项附件：">
                    <div style="width: 600px">
                        <el-tag style="margin: 0 10px 10px 0" v-for="(file, index) in order.files" :key="index" disable-transitions closable @close="addOrder('order-file-delete', file)">{{ file.name }}</el-tag>
                    </div>
                    <el-button type="plain" icon="el-icon-plus" @click="addOrder('order-file-upload', 'image')">选择图片</el-button>
                    <el-button type="plain" icon="el-icon-plus" @click="addOrder('order-file-upload', 'document')">选择文档</el-button>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" icon="el-icon-check" @click="addOrder('submit')">提交</el-button>
                    <el-button type="plain" icon="el-icon-close" @click="addOrder('end')">放弃</el-button>
                </el-form-item>
            </el-form>
        </comp-dialog>
        <comp-dialog title="选择企业/项目" width="80vw" height="80vh" ref="companyPicker">
            <comp-companys style="height: 100%" ref="companyPickerList" limit="employee" v-if="order">
                <template #body="scope">
                    <el-button type="primary" size="mini" icon="el-icon-check" @click.stop="addOrder('order-company', scope.data.id)">选择</el-button>
                </template>
                <template #foot="scope">
                    <el-button type="danger" size="small" icon="el-icon-close" @click="addOrder('order-company-end')">放弃</el-button>
                </template>
            </comp-companys>
        </comp-dialog>
    </div>
</template>

<script>
    import mixin from "../mixin";
    import { string, int, selectFile } from "../util";
    export default {
        name: "page-staff-work-order-add",
        title: "提交事项",
        nodes: ["/menu/staff-work"],
        childs: [],
        mixins: [mixin],
        data: () => ({
            loading: false,
            order: null,
            tags: [],
            handlers: [],
        }),
        methods: {
            addOrder(action, data) {
                if (this.loading) return;
                let query = this.$route.query;
                let order = this.order;
                let tags = this.tags;
                let handlers = this.handlers;
                if (action === "start" || !action) {
                    this.loading = true;
                    this.plugins.user.call(async () => {
                        if (tags.length > 0) { }
                        else tags = await this.plugins.user.getOrderOfTags().then((res) => res.code === 0 ? res.data : []);
                        return { code: 0 };
                    }).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.order = this.plugins.user.formatOrder();
                            this.order.status = "published";
                            this.tags = tags;
                            this.handlers = [];
                            this.addOrder("validate");
                            this.$refs.order.init();
                            if (query.companyId) this.addOrder("order-company", query.companyId);
                        } else {
                            this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "validate") {
                    let error = "";
                    error = error || (order.company.id ? "" : "请先选择企业/项目！");
                    // order.dept.id = string(() => order.company.depts.find((dept) => dept.id === order.dept.id).id);
                    order.lev = string(order.lev);

                    // error = error || (order.dept.id ? "" : "请先选择负责工作队！");
                    // order.handler.id = string(() => handlers.find((handler) => handler.id === order.handler.id).id);
                    // error = error || (order.handler.id ? "" : "请先选择负责服务专员！");
                    order.title = string(order.title).trim();
                    error = error || (order.title ? "" : "请先输入事项标题！");
                    order.content = string(order.content).trim();
                    error = error || (order.content ? "" : "请先输入事项描述！");
                    order.tags = tags.filter((tag) => tag.selected);
                    error = error || (order.tags.length == 1 ? "" : "事项分类必填！");
                    if (data) this.plugins.modal.toast(error, "error");
                    return !error;
                } else if (action === "order-company") {
                    let companyId = data;
                    if (companyId) {
                        this.loading = true;
                        this.plugins.user.getCompany(companyId).then((res) => {
                            this.loading = false;
                            if (res.code === 0) {
                                order.company = res.data;
                                order.dept.id = "";
                                order.dept.name = "";
                                order.handler.id = "";
                                order.handler.name = "";
                                handlers.splice(0);
                                this.addOrder("validate");
                                this.addOrder("order-company-end");
                            } else {
                                order.company = this.plugins.user.formatCompany();
                                order.dept.id = "";
                                order.dept.name = "";
                                order.handler.id = "";
                                order.handler.name = "";
                                handlers.splice(0);
                                this.addOrder("validate");
                                this.addOrder("order-company-end");
                                this.plugins.modal.toast("加载失败<br>" + res.code + "：" + res.msg, "error");
                            }
                        });
                    } else {
                        this.$refs.companyPicker.init();
                        this.$nextTick(() => this.$refs.companyPickerList.init());
                    }
                } else if (action === "order-company-end") {
                    this.$refs.companyPicker.close();
                } else if (action === "order-dept") {
                    handlers.splice(0);
                    for (let helper of order.company.helpers) {
                        let handler = helper.client;
                        let depment = handler.depments.find((depment) => depment.dept.id === order.dept.id);
                        if (depment) handler.flag = depment.duty + " - " + handler.name;
                        if (depment) handlers.push(handler);
                    }
                    this.addOrder("validate");
                } else if (action === "order-file-upload") {
                    let type = data;
                    let timer = null;
                    let progress = (event) => timer = clearTimeout(timer) || setTimeout(() => this.plugins.modal.toast("上传进度：" + event.percent + "%", "info"), 200);
                    let upload = (type, file) => {
                        this.loading = true;
                        this.plugins.user.uploadFile(file, type, progress).then((res) => {
                            this.loading = false;
                            if (res.code === 0) {
                                order.files.push(res.data);
                                this.addOrder("validate");
                            } else {
                                this.plugins.modal.alert("上传失败", res.code + "：" + res.msg, "error");
                            }
                        });
                    };
                    if (type === "image") selectFile("image/*").then((file) => {
                        if (file.size > 5 * 1048576) this.plugins.modal.toast("图片过大，不能大于5MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                    if (type === "document") selectFile(".xls,.xlsx,.doc,.docx,.pdf").then((file) => {
                        if (file.size > 10 * 1048576) this.plugins.modal.toast("文档过大，不能大于10MB哦！请重新选择。", "error");
                        else upload(type, file);
                    });
                } else if (action === "order-file-delete") {
                    let file = data;
                    let index = order.files.indexOf(file);
                    if (index > -1) order.files.splice(index, 1);
                } else if (action === "submit") {
                    if (!this.addOrder("validate", true)) return;
                    this.loading = true;
                    this.plugins.user.addOrder(order).then((res) => {
                        this.loading = false;
                        if (res.code === 0) {
                            this.plugins.modal.toast("提交成功！", "success");
                            this.addOrder("end");
                            this.$nextTick(() => this.$router.replace("/staff/work/order?orderId=" + res.data.id));
                        } else {
                            this.plugins.modal.alert("提交失败", res.code + "：" + res.msg, "error");
                        }
                    });
                } else if (action === "end") {
                    this.$refs.order.close();
                    this.$router.back();
                }
            },
            destroy() {
                if (this.loading) return;
                return true;
            },
            init() {
                if (this.loading) return;
                this.loading = true;
                this.$root.$refs.navbar.init();
                this.plugins.user.call(async () => {
                    let res = await this.plugins.user.init();
                    if (res.code === 0) { }
                    return res;
                }, async () => {
                    if (this.access(this.$route.name)) return { code: 0 };
                    return this.env.xhrErrors.find((error) => error.code === 4);
                }).then((res) => {
                    this.loading = false;
                    this.$root.$refs.navbar.init();
                    if (res.code === 0) {
                        this.addOrder();
                    } else if (res.code === 2) {
                        this.$root.$refs.navbar.login();
                    } else {
                        this.plugins.modal.alert("页面加载失败", res.code + "：" + res.msg, "error").then(() => this.$router.replace("/staff/work/orders/type1"));
                    }
                });
            },
        },
    };
</script>

<style lang="scss">
    .page-staff-work-order-add {
        overflow: hidden;
    }
</style>